package cn.yfj.basic.interceptor;

import cn.yfj.basic.jwt.JwtUtils;
import cn.yfj.basic.jwt.LoginData;
import cn.yfj.basic.jwt.Payload;
import cn.yfj.basic.util.RsaUtils;
import cn.yfj.org.mapper.EmployeeMapper;
import cn.yfj.system.anno.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Value("${jwt.rsa.pub}")//SEL
    private String pubKey;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求中的token
        String jwtToken = request.getHeader("U-TOKEN");
        //校验token不能为空
        if (!StringUtils.isEmpty(jwtToken)) {
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pubKey).getFile());
            Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
            if (payload != null) {
                //查看这个人是否有访问权限
                LoginData loginData = payload.getLoginData();
                if (loginData.getUser() != null) {
                    //前端用户直接放行
                    return true;
                }
                //后端员工
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                //判断方法上面是否打的有注解
                PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                if (preAuthorize == null) {//没打注解直接放行不需要校验权限
                    return true;
                }
                String sn = preAuthorize.value();
                //查询当前登录人所拥有权限
                List<String> ownpermissions = loginData.getPermissions();
                if (ownpermissions.contains(sn)) {//包含
                    return true;
                }//没有权限
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("{\"success\":false,\"message\":\"noPermission\"}");
                writer.flush();
                writer.close();
                return false;//阻止放行

            }
        }
        //这里不能直接报错，需要返回AjaxResult响应给前端，不能直接返回AjaxResult
        // 应该将AjaxResult 写入到response的流中
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻止放行
    }

    }
/*
        //检验token不能为空
        //在Redis中获取值
        if(!token.isEmpty()){
            Object loginTmp = redisTemplate.opsForValue().get(token);
            */
/*拿的到*//*

            if(loginTmp!=null){
                */
/*刷新过期时间*//*

                redisTemplate.opsForValue().set(
                        token,
                        loginTmp,
                        30,
                        TimeUnit.MINUTES
                );
                Logininfo logininfo = (Logininfo)loginTmp;
                //如果是用户来访问直接放行
                if(logininfo.getType()==1){
                    return true;
                }
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                PreAuthorize ann = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                if (ann==null){//如果没打注解的为公共资源直接放行
                    return true;
                }
                String value = ann.value();
                List<String> ownPermissions =employeeMapper.loadPerssionSnByLogininfoId(logininfo.getId());
                if (ownPermissions.contains(value)) {
                    */
/*放行*//*

                    return true;
                }
                //将ajaxresult写入response流中
                */
/*设置格式*//*

                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                //内容
                writer.println("{\"success\":false,\"message\":\"nopermission\"}");
                writer.flush();
                writer.close();
                return false;
            }

        }
        //将ajaxresult写入response流中
        */
/*设置格式*//*

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //内容
        writer.println("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
*/
